<template>
  <div class="root">
    <ToolbarPanel ref="toolbar" v-if="!isView" />
    <div style="display: flex">
      <ItemPanel ref="addItemPanel" v-if="!isView" :height="height" />
      <div
        ref="canvas"
        class="canvasPanel"
        :style="{
          height: height + 'px',
          width: isView ? '100%' : '70%',
          'border-bottom': isView ? 0 : null,
        }"
      ></div>
      <DetailPanel
        ref="detailPanel"
        v-if="!isView"
        :height="height"
        :model="selectedModel"
        :readOnly="mode !== 'edit'"
        :users="users"
        :groups="groups"
        :signalDefs="processModel.signalDefs"
        :messageDefs="processModel.messageDefs"
        :onChange="
          (key, val) => {
            onItemCfgChange(key, val);
          }
        "
      />
    </div>
  </div>
</template>
<script>
import G6 from "@antv/g6/src";
import { getShapeName } from "../util/clazz";
import Command from "../plugins/command";
import Toolbar from "../plugins/toolbar";
import AddItemPanel from "../plugins/addItemPanel";
import CanvasPanel from "../plugins/canvasPanel";
import ToolbarPanel from "../components/ToolbarPanel";
import ItemPanel from "../components/ItemPanel";
import DetailPanel from "../components/DetailPanel";
import i18n from "../locales";
import { exportXML } from "../util/bpmn";
import registerShape from "../shape";
import registerBehavior from "../behavior";
registerShape(G6);
registerBehavior(G6);
export default {
  name: "wfd-vue",
  components: {
    ToolbarPanel,
    ItemPanel,
    DetailPanel,
  },
  provide() {
    return {
      i18n: i18n[this.lang],
    };
  },
  props: {
    isView: {
      type: Boolean,
      default: false,
    },
    mode: {
      type: String,
      default: "edit",
    },
    height: {
      type: Number,
      default: 800,
    },
    lang: {
      type: String,
      default: "zh",
    },
    data: {
      type: Object,
      default: () => ({ nodes: [], edges: [] }),
    },
    users: {
      type: Array,
      default: () => [],
    },
    groups: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      resizeFunc: () => {},
      selectedModel: {},
      processModel: {
        id: "",
        name: "",
        clazz: "process",
        dataObjs: [],
        signalDefs: [],
        messageDefs: [],
      },
      graph: null,
      cmdPlugin: null,
    };
  },
  watch: {
    // data:{
    // handler(oldData, newData) {
    //   // console.log(newData,oldData)
    //   if(oldData !== newData) {
    //     // this.initEvents()
    //     if (this.graph) {
    //       this.graph.changeData(this.initShape(newData));
    //       this.graph.setMode(this.mode);
    //       this.graph.emit('canvas:click');
    //       if (this.cmdPlugin) {
    //         this.cmdPlugin.initPlugin(this.graph);
    //       }
    //       if (this.isView) {
    //         this.graph.fitView(5)
    //       }
    //     }
    //   }
    // },
    // deep: true,
    // immediate: true,
    // },
    data(oldData, newData) {
      if (oldData !== newData) {
        console.log("改变了");
        this.initEvents();
        // this.updated()
        if (this.graph) {
          this.graph.changeData(this.initShape(newData));
          this.graph.setMode(this.mode);
          this.graph.emit("canvas:click");
          if (this.cmdPlugin) {
            this.cmdPlugin.initPlugin(this.graph);
          }
          if (this.isView) {
            this.graph.fitView(5);
          }
        }
        this.$forceUpdate();
      }
    },
  },
  methods: {
    init() {
      // 初始化默认显示流程内容
      this.selectedModel = this.processModel;
      let plugins = [];
      if (!this.isView) {
        this.cmdPlugin = new Command();
        const toolbar = new Toolbar({ container: this.$refs["toolbar"].$el });
        const addItemPanel = new AddItemPanel({
          container: this.$refs["addItemPanel"].$el,
        });
        const canvasPanel = new CanvasPanel({
          container: this.$refs["canvas"],
        });
        plugins = [this.cmdPlugin, toolbar, addItemPanel, canvasPanel];
      }
      const width = this.$refs["canvas"].offsetWidth;
      this.graph = new G6.Graph({
        plugins: plugins,
        container: this.$refs["canvas"],
        height: this.height - 1,
        width: width,
        modes: {
          default: ["drag-canvas", "clickSelected"],
          view: [],
          edit: [
            "drag-canvas",
            "hoverNodeActived",
            "hoverAnchorActived",
            "dragNode",
            "dragEdge",
            "dragPanelItemAddNode",
            "clickSelected",
            "deleteItem",
            "itemAlign",
          ],
        },
        defaultEdge: {
          shape: "flow-polyline-round",
        },
      });
      // console.log(this.graph.save())

      this.graph.saveXML = (createFile = false) =>
        exportXML(this.graph.save(), this.processModel, createFile);
      if (this.isView) this.graph.setMode("view");
      else this.graph.setMode(this.mode);
      // console.log(this.data)
      this.graph.data(this.initShape(this.data));
      this.graph.render();
      if (this.isView && this.data && this.data.nodes) {
        this.graph.fitView(5);
      }
      this.initEvents();
    },
    getVal() {
      return this.processModel;
    },
    initShape(data) {
      // console.log(data);
      if (data && data.nodes) {
        return {
          nodes: data.nodes.map((node) => {
            return {
              shape: getShapeName(node.clazz),
              ...node,
            };
          }),
          edges: data.edges,
        };
      }
      return data;
    },
    initEvents() {
      this.graph.on("afteritemselected", (items) => {
        if (items && items.length > 0) {
          const item = this.graph.findById(items[0]);
          this.selectedModel = { ...item.getModel() };
          this.$forceUpdate();
          // console.log(99999999)
          // console.log(this.selectedModel)
          // this.$set(this.selectedModel, "funcArr", []);
        } else {
          this.selectedModel = this.processModel;
          this.$forceUpdate();
        }
      });
      const page = this.$refs["canvas"];
      const graph = this.graph;
      const height = this.height - 1;
      this.resizeFunc = () => {
        graph.changeSize(page.offsetWidth, height);
      };
      window.addEventListener("resize", this.resizeFunc);
    },
    onItemCfgChange(key, value) {
      if (key == "itemField") {
        let values = value;
        if (this.selectedModel.hasOwnProperty("itemField")) {
          let result1 = values.filter(
            (item) =>
              !this.selectedModel.itemField.some((ele) => ele.fileName === item)
          );
          let result2 = this.selectedModel.itemField.filter(
            (item) => !values.some((ele) => ele === item.fileName)
          );
          // console.log(result1);
          // console.log(result2);
          let obj = {};
          if (result1.length > 0) {
            obj = {
              fileName: result1[0],
              compareSymbol: "",
              fileValue: "",
            };
            values = this.selectedModel.itemField;
            values.push(obj);
          }
          if (result2.length > 0) {
            values = this.selectedModel.itemField;
            values = this.selectedModel.itemField.filter((item) => {
              return !result2[0].fileName.includes(item.fileName);
            });
          }
          console.log(values);
        }
        this.$forceUpdate();
        const items = this.graph.get("selectedItems");
        if (items && items.length > 0) {
          const item = this.graph.findById(items[0]);
          if (key == "itemField") {
            this.graph.executeCommand("update", {
              itemId: items[0],
              // updateModel: { [key]: value},

              updateModel: { itemArr: value },
            });
          }
          if (this.graph.executeCommand) {
            // this.graph.executeCommand("update", {
            //   itemId: items[0],
            //   updateModel: { [key]: value },
            // });
            if (
              key == "itemField" &&
              !this.selectedModel.hasOwnProperty("itemField")
            ) {
              let params = values.map((i) => {
                return {
                  fileName: i,
                  compareSymbol: i.compareSymbol ? i.compareSymbol : "",
                  fileValue: i.fileValue ? i.fileValue : "",
                };
              });
              this.graph.executeCommand("update", {
                itemId: items[0],
                // updateModel: { funcArr: value},
                updateModel: { [key]: params, itemArr: value },
              });
            } else {
              this.graph.executeCommand("update", {
                itemId: items[0],
                updateModel: { [key]: values },
              });
            }
          } else {
            this.graph.updateItem(item, { [key]: value });
          }
          this.selectedModel = { ...item.getModel() };
          let arr = [];
          arr = this.graph.save().nodes;
          arr.forEach((item) => {
            if (item.hasOwnProperty("isDefault") && item.isDefault == 1) {
              if (item.hasOwnProperty("itemFormFlag")) {
                delete item.itemFormFlag;
              }
              if (item.hasOwnProperty("readOnly")) {
                delete item.readOnly;
              }
              if (item.hasOwnProperty("flowFormFlag")) {
                delete item.flowFormFlag;
              }
              if (item.hasOwnProperty("readOnlys")) {
                delete item.readOnlys;
              }
            }
            if (item.hasOwnProperty("isDefault") && item.isDefault == 0) {
              if (item.hasOwnProperty("url")) {
                delete item.pageUrl;
              }
            }
            this.$set(this.graph.save(), "nodes", arr);
          });
          // 过滤数据更新
          if (this.selectedModel.isDefault == 1) {
            if (this.selectedModel.hasOwnProperty("itemFormFlag")) {
              delete this.selectedModel.itemFormFlag;
            }
            if (this.selectedModel.hasOwnProperty("readOnly")) {
              delete this.selectedModel.readOnly;
            }
            if (this.selectedModel.hasOwnProperty("flowFormFlag")) {
              delete this.selectedModel.flowFormFlag;
            }
            if (this.selectedModel.hasOwnProperty("readOnlys")) {
              delete this.selectedModel.readOnlys;
            }
          } else {
            if (this.selectedModel.hasOwnProperty("url")) {
              delete this.selectedModel.pageUrl;
            }
          }
          console.log(this.selectedModel);
          this.$forceUpdate();
        } else {
          const canvasModel = { ...this.processModel, [key]: value };
          this.selectedModel = canvasModel;
          this.processModel = canvasModel;
        }
      } else if(key == "systemField"){
         let values = value;
        if (this.selectedModel.hasOwnProperty("systemField")) {
          let result1 = values.filter(
            (item) =>
              !this.selectedModel.systemField.some((ele) => ele.fileName === item)
          );
          let result2 = this.selectedModel.systemField.filter(
            (item) => !values.some((ele) => ele === item.fileName)
          );
          // console.log(result1);
          // console.log(result2);
          let obj = {};
          if (result1.length > 0) {
            obj = {
              fileName: result1[0],
              compareSymbol: "",
              fileValue: "",
            };
            values = this.selectedModel.systemField;
            values.push(obj);
          }
          if (result2.length > 0) {
            values = this.selectedModel.systemField;
            values = this.selectedModel.systemField.filter((item) => {
              return !result2[0].fileName.includes(item.fileName);
            });
          }
          console.log(values);
        }
        this.$forceUpdate();
        const items = this.graph.get("selectedItems");
        if (items && items.length > 0) {
          const item = this.graph.findById(items[0]);
          if (key == "itemField") {
            this.graph.executeCommand("update", {
              itemId: items[0],
              // updateModel: { [key]: value},

              updateModel: { systemArr: value },
            });
          }
          if (this.graph.executeCommand) {
            // this.graph.executeCommand("update", {
            //   itemId: items[0],
            //   updateModel: { [key]: value },
            // });
            if (
              key == "systemField" &&
              !this.selectedModel.hasOwnProperty("systemField")
            ) {
              let params = values.map((i) => {
                return {
                  fileName: i,
                  compareSymbol: i.compareSymbol ? i.compareSymbol : "",
                  fileValue: i.fileValue ? i.fileValue : "",
                };
              });
              this.graph.executeCommand("update", {
                itemId: items[0],
                // updateModel: { funcArr: value},
                updateModel: { [key]: params, systemArr: value },
              });
            } else {
              this.graph.executeCommand("update", {
                itemId: items[0],
                updateModel: { [key]: values },
              });
            }
          } else {
            this.graph.updateItem(item, { [key]: value });
          }
          this.selectedModel = { ...item.getModel() };
          let arr = [];
          arr = this.graph.save().nodes;
          arr.forEach((item) => {
            if (item.hasOwnProperty("isDefault") && item.isDefault == 1) {
              if (item.hasOwnProperty("itemFormFlag")) {
                delete item.itemFormFlag;
              }
              if (item.hasOwnProperty("readOnly")) {
                delete item.readOnly;
              }
              if (item.hasOwnProperty("flowFormFlag")) {
                delete item.flowFormFlag;
              }
              if (item.hasOwnProperty("readOnlys")) {
                delete item.readOnlys;
              }
            }
            if (item.hasOwnProperty("isDefault") && item.isDefault == 0) {
              if (item.hasOwnProperty("url")) {
                delete item.pageUrl;
              }
            }
            this.$set(this.graph.save(), "nodes", arr);
          });
          // 过滤数据更新
          if (this.selectedModel.isDefault == 1) {
            if (this.selectedModel.hasOwnProperty("itemFormFlag")) {
              delete this.selectedModel.itemFormFlag;
            }
            if (this.selectedModel.hasOwnProperty("readOnly")) {
              delete this.selectedModel.readOnly;
            }
            if (this.selectedModel.hasOwnProperty("flowFormFlag")) {
              delete this.selectedModel.flowFormFlag;
            }
            if (this.selectedModel.hasOwnProperty("readOnlys")) {
              delete this.selectedModel.readOnlys;
            }
          } else {
            if (this.selectedModel.hasOwnProperty("url")) {
              delete this.selectedModel.pageUrl;
            }
          }
          console.log(this.selectedModel);
          this.$forceUpdate();
        } else {
          const canvasModel = { ...this.processModel, [key]: value };
          this.selectedModel = canvasModel;
          this.processModel = canvasModel;
        }
      }else {
        const items = this.graph.get("selectedItems");
        if (items && items.length > 0) {
          const item = this.graph.findById(items[0]);
          if (this.graph.executeCommand) {
            this.graph.executeCommand("update", {
              itemId: items[0],
              updateModel: { [key]: value },
            });
          } else {
            this.graph.updateItem(item, { [key]: value });
          }
          this.selectedModel = { ...item.getModel() };
          let arr = [];
          arr = this.graph.save().nodes;
          arr.forEach((item) => {
            if (item.hasOwnProperty("isDefault") && item.isDefault == 1) {
              if (item.hasOwnProperty("itemFormFlag")) {
                delete item.itemFormFlag;
              }
              if (item.hasOwnProperty("readOnly")) {
                delete item.readOnly;
              }
              if (item.hasOwnProperty("flowFormFlag")) {
                delete item.flowFormFlag;
              }
              if (item.hasOwnProperty("readOnlys")) {
                delete item.readOnlys;
              }
            }
            if (item.hasOwnProperty("isDefault") && item.isDefault == 0) {
              if (item.hasOwnProperty("url")) {
                delete item.pageUrl;
              }
            }
            this.$set(this.graph.save(), "nodes", arr);
          });
          // 过滤数据更新
          if (this.selectedModel.isDefault == 1) {
            if (this.selectedModel.hasOwnProperty("itemFormFlag")) {
              delete this.selectedModel.itemFormFlag;
            }
            if (this.selectedModel.hasOwnProperty("readOnly")) {
              delete this.selectedModel.readOnly;
            }
            if (this.selectedModel.hasOwnProperty("flowFormFlag")) {
              delete this.selectedModel.flowFormFlag;
            }
            if (this.selectedModel.hasOwnProperty("readOnlys")) {
              delete this.selectedModel.readOnlys;
            }
          } else {
            if (this.selectedModel.hasOwnProperty("url")) {
              delete this.selectedModel.pageUrl;
            }
          }
          this.$forceUpdate();
        } else {
          const canvasModel = { ...this.processModel, [key]: value };
          this.selectedModel = canvasModel;
          this.processModel = canvasModel;
        }
      }
    },
  },
  destroyed() {
    window.removeEventListener("resize", this.resizeFunc);
    this.graph.getNodes().forEach((node) => {
      node.getKeyShape().stopAnimate();
    });
  },
  mounted() {
    this.init();
  },
};
</script>
<style lang="scss" scoped>
.root {
  width: 100%;
  height: 100%;
  background-color: #fff;
  display: block;
}
.canvasPanel {
  flex: 0 0 auto;
  float: left;
  width: 70%;
  background-color: #fff;
  border-bottom: 1px solid #e9e9e9;
}
</style>
